<template>
  <div class="playback-view">
    <div class="header">
      <h2>视频回放</h2>
    </div>

    <div class="content">
      <!-- 摄像头列表 -->
      <div class="camera-list" v-if="!selectedCamera">
        <h3>选择摄像头</h3>
        
        <!-- 空状态 -->
        <div v-if="cameras.length === 0" class="empty-camera-state">
          <a-empty description="暂无摄像头数据">
            <template #image>
              <VideoCameraOutlined style="font-size: 64px; color: #d9d9d9;" />
            </template>
            <a-button type="primary" @click="refreshCameras">
              <template #icon><ReloadOutlined /></template>
              刷新摄像头
            </a-button>
          </a-empty>
        </div>
        
        <!-- 摄像头网格 -->
        <a-row v-else :gutter="[16, 16]">
          <a-col :span="6" v-for="camera in cameras" :key="camera.id">
            <a-card 
              hoverable 
              @click="selectCamera(camera)"
              :class="{ 'selected': false }"
            >
              <template #cover>
                <div class="camera-preview">
                  <video 
                    v-if="camera.status === 'online'"
                    :src="camera.streamUrl"
                    muted
                    playsinline
                    preload="metadata"
                  ></video>
                  <div v-else class="offline-preview">
                    <ExclamationCircleOutlined />
                  </div>
                </div>
              </template>
              <a-card-meta>
                <template #title>{{ camera.name }}</template>
                <template #description>
                  <a-tag :color="camera.status === 'online' ? 'green' : 'red'">
                    {{ camera.status === 'online' ? '在线' : '离线' }}
                  </a-tag>
                </template>
              </a-card-meta>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 录像列表和播放器 -->
      <div class="playback-content" v-else>
        <div class="back-button">
          <a-button @click="goBack" :icon="h(ArrowLeftOutlined)">
            返回摄像头列表
          </a-button>
        </div>

        <div class="selected-camera-info">
          <h3>{{ selectedCamera.name }} - 历史录像</h3>
          <a-tag :color="selectedCamera.status === 'online' ? 'green' : 'red'">
            {{ selectedCamera.status === 'online' ? '在线' : '离线' }}
          </a-tag>
        </div>

        <div class="playback-layout">
          <!-- 录像列表 -->
          <div class="recordings-list">
            <div class="list-header">
              <h4>录像列表</h4>
              <div class="time-range-selector">
                <a-range-picker 
                  v-model:value="dateRange"
                  @change="handleDateChange"
                  format="YYYY-MM-DD HH:mm:ss"
                  :show-time="{ format: 'HH:mm:ss' }"
                />
                <a-button @click="loadRecordingsWithTimeRange" type="primary" style="margin-left: 8px;">
                  查询录像
                </a-button>
              </div>
            </div>
            
            <!-- 空状态 -->
            <div v-if="!loading && filteredRecordings.length === 0" class="empty-recordings">
              <a-empty description="暂无录像文件">
                <template #image>
                  <PlayCircleOutlined style="font-size: 48px; color: #d9d9d9;" />
                </template>
                <a-button type="primary" @click="loadRecordings(selectedCamera!.name)">
                  <template #icon><ReloadOutlined /></template>
                  重新加载
                </a-button>
              </a-empty>
            </div>
            
            <!-- 录像列表 -->
            <div class="recordings-content" v-if="!loading && filteredRecordings.length > 0">
              <a-list
                :data-source="filteredRecordings"
                :loading="loading"
                :pagination="{
                  pageSize: 10,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
                }"
              >
              <template #renderItem="{ item }">
                <a-list-item @click="playRecording(item)" class="recording-item">
                  <a-list-item-meta>
                    <template #title>
                      <div class="recording-title">
                        <span>{{ item.name }}</span>
                        <a-tag :color="item.type === 'motion' ? 'orange' : 'blue'">
                          {{ item.type === 'motion' ? '移动检测' : '定时录像' }}
                        </a-tag>
                      </div>
                    </template>
                    <template #description>
                      <div class="recording-info">
                        <div>开始时间: {{ item.startTime }}</div>
                        <div>结束时间: {{ item.endTime }}</div>
                        <div>时长: {{ item.duration }}</div>
                      </div>
                    </template>
                  </a-list-item-meta>
                  <template #actions>
                    <a-button type="link" size="small" @click.stop="downloadRecording(item)">
                      <DownloadOutlined />
                    </a-button>
                  </template>
                </a-list-item>
              </template>
              </a-list>
            </div>
          </div>

          <!-- 视频播放器 -->
          <div class="video-player">
            <div class="player-header">
              <h4>视频播放</h4>
              <div class="player-controls">
                <a-button @click="toggleFullscreen" :icon="h(FullscreenOutlined)">
                  全屏
                </a-button>
              </div>
            </div>
            
            <div class="player-container" ref="playerContainer">
              <video 
                v-if="currentRecording"
                ref="videoPlayer"
                :src="currentRecording.url"
                controls
                preload="metadata"
                @loadedmetadata="handleVideoLoaded"
                @error="handlePlaybackError"
              >
                您的浏览器不支持视频播放
              </video>
              <div v-else class="no-video">
                <PlayCircleOutlined />
                <p>请选择一个录像文件进行播放</p>
              </div>
            </div>
            
            <div class="player-info" v-if="currentRecording">
              <div class="recording-details">
                <h5>{{ currentRecording.name }}</h5>
                <p>开始时间: {{ currentRecording.startTime }}</p>
                <p>结束时间: {{ currentRecording.endTime }}</p>
                <p>时长: {{ currentRecording.duration }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, h, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { 
  ExclamationCircleOutlined, 
  ArrowLeftOutlined, 
  DownloadOutlined, 
  FullscreenOutlined,
  PlayCircleOutlined,
  VideoCameraOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue'
import dayjs, { Dayjs } from 'dayjs'
import { cameraApi, CameraDataConverter, type Camera, type RecordingItem } from '@/services/api'


const selectedCamera = ref<Camera | null>(null)
const currentRecording = ref<RecordingItem | null>(null)
const loading = ref(false)
const dateRange = ref<[Dayjs, Dayjs] | null>(null)
const playerContainer = ref<HTMLElement>()
const videoPlayer = ref<HTMLVideoElement>()

const cameras = ref<Camera[]>([])
const recordings = ref<RecordingItem[]>([])

const filteredRecordings = computed(() => {
  if (!selectedCamera.value) return []
  
  let filtered = recordings.value.filter(recording => 
    recording.cameraId === selectedCamera.value!.id
  )
  
  if (dateRange.value) {
    const [start, end] = dateRange.value
    filtered = filtered.filter(recording => {
      const recordDate = dayjs(recording.date)
      return recordDate.isAfter(start.subtract(1, 'day')) && recordDate.isBefore(end.add(1, 'day'))
    })
  }
  
  return filtered.sort((a, b) => dayjs(b.startTime).valueOf() - dayjs(a.startTime).valueOf())
})

const selectCamera = async (camera: Camera) => {
  selectedCamera.value = camera
  currentRecording.value = null
  
  // 设置默认时间范围：当前时间往前72小时
  const now = dayjs()
  const seventyTwoHoursAgo = now.subtract(72, 'hour')
  dateRange.value = [seventyTwoHoursAgo, now]
  
  // 获取该摄像头的录像数据
  await loadRecordings(camera.name)
}

const loadRecordings = async (cameraName: string) => {
  loading.value = true
  try {
    // 使用默认的72小时时间范围
    const now = dayjs()
    const seventyTwoHoursAgo = now.subtract(72, 'hour')
    
    const recordingFiles = await cameraApi.getRecordingsByTimeRange(
      cameraName,
      seventyTwoHoursAgo.toISOString(),
      now.toISOString()
    )
    
    recordings.value = CameraDataConverter.recordingFilesToRecordingItems(recordingFiles, cameraName)
    message.success(`成功获取 ${recordings.value.length} 个录像文件`)
  } catch (error) {
    console.error('获取录像列表失败:', error)
    message.error(`获取录像列表失败: ${error instanceof Error ? error.message : '未知错误'}`)
    recordings.value = []
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  selectedCamera.value = null
  currentRecording.value = null
}

const playRecording = (recording: RecordingItem) => {
  currentRecording.value = recording
  message.success(`开始播放: ${recording.name}`)
}

const downloadRecording = (recording: RecordingItem) => {
  try {
    // 创建下载链接
    const link = document.createElement('a')
    link.href = recording.url
    link.download = recording.name
    link.target = '_blank'
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    message.success(`开始下载: ${recording.name}`)
  } catch (error) {
    console.error('下载失败:', error)
    message.error('下载失败，请重试')
  }
}

const handleDateChange = () => {
  // 日期范围改变时的处理
}

const loadRecordingsWithTimeRange = async () => {
  if (!selectedCamera.value) {
    message.warning('请先选择摄像头')
    return
  }
  
  if (!dateRange.value || dateRange.value.length !== 2) {
    message.warning('请选择时间范围')
    return
  }
  
  loading.value = true
  try {
    const [start, end] = dateRange.value
    
    const recordingFiles = await cameraApi.getRecordingsByTimeRange(
      selectedCamera.value.name,
      start.toISOString(),
      end.toISOString()
    )
    
    recordings.value = CameraDataConverter.recordingFilesToRecordingItems(recordingFiles, selectedCamera.value.name)
    message.success(`成功获取 ${recordings.value.length} 个录像文件`)
  } catch (error) {
    console.error('获取录像列表失败:', error)
    message.error(`获取录像列表失败: ${error instanceof Error ? error.message : '未知错误'}`)
    recordings.value = []
  } finally {
    loading.value = false
  }
}

const handleVideoLoaded = () => {
  message.success('视频加载完成')
}

const handlePlaybackError = () => {
  message.error('视频播放失败')
}

const refreshCameras = async (showMessage: boolean = true) => {
  loading.value = true
  try {
    const pathList = await cameraApi.getPathsList(0, 1000) // 获取所有摄像头
    cameras.value = CameraDataConverter.pathsToCameras(pathList.items)
    if (showMessage) {
      message.success(`成功获取 ${cameras.value.length} 个摄像头`)
    }
  } catch (error) {
    console.error('获取摄像头列表失败:', error)
    if (showMessage) {
      message.error(`获取摄像头列表失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
    // 如果API调用失败，使用空数组
    cameras.value = []
  } finally {
    loading.value = false
  }
}

const toggleFullscreen = () => {
  if (!playerContainer.value) return
  
  if (!document.fullscreenElement) {
    playerContainer.value.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

// 页面加载时自动获取摄像头列表
onMounted(() => {
  refreshCameras(false) // 首次加载不显示消息
})
</script>

<style scoped>
.playback-view {
  min-height: calc(100vh - 0px);
  padding: 24px;
  background: #fff;
}

.header {
  margin-bottom: 24px;
}

.header h2 {
  margin: 0;
  color: #1890ff;
}

.content {
  min-height: calc(100vh - 120px);
}

.camera-list h3 {
  margin-bottom: 16px;
  color: #262626;
}

.empty-camera-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}

.camera-preview {
  height: 120px;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.camera-preview video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.offline-preview {
  color: #999;
  font-size: 32px;
}

.selected {
  border-color: #1890ff !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.back-button {
  margin-bottom: 16px;
}

.selected-camera-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
}

.selected-camera-info h3 {
  margin: 0;
  color: #262626;
}

.playback-layout {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  min-height: calc(100vh - 300px); /* 改为min-height确保有足够空间 */
}

.recordings-list {
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  overflow: visible; /* 改为visible以显示分页栏 */
  display: flex;
  flex-direction: column;
}

.recordings-content {
  flex: 1;
  overflow: visible;
  padding: 0 16px 16px 16px; /* 为分页栏留出空间 */
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f5f5f5;
  border-bottom: 1px solid #d9d9d9;
}

.list-header h4 {
  margin: 0;
  color: #262626;
}

.time-range-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.empty-recordings {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}

.recording-item {
  cursor: pointer;
  transition: background-color 0.3s;
}

.recording-item:hover {
  background-color: #f5f5f5;
}

.recording-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recording-info {
  color: #8c8c8c;
  font-size: 12px;
}

.recording-info div {
  margin-bottom: 4px;
}

.video-player {
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: fit-content; /* 根据内容调整高度 */
  max-height: 500px; /* 设置最大高度 */
}

.player-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f5f5f5;
  border-bottom: 1px solid #d9d9d9;
}

.player-header h4 {
  margin: 0;
  color: #262626;
}

.player-container {
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400px; /* 固定高度，避免被拉伸 */
  aspect-ratio: 16/9; /* 保持16:9比例 */
}

.player-container video {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 保持视频比例，避免拉伸 */
}

.no-video {
  color: #999;
  text-align: center;
}

.no-video .anticon {
  font-size: 48px;
  margin-bottom: 16px;
}

.player-info {
  padding: 16px;
  background: #f5f5f5;
  border-top: 1px solid #d9d9d9;
}

.recording-details h5 {
  margin: 0 0 8px 0;
  color: #262626;
}

.recording-details p {
  margin: 4px 0;
  color: #8c8c8c;
  font-size: 12px;
}

@media (max-width: 1200px) {
  .playback-layout {
    grid-template-columns: 1fr;
    min-height: auto; /* 改为min-height */
  }
  
  .video-player {
    max-height: 450px; /* 小屏幕时稍微增加高度 */
  }
  
  .player-container {
    height: 350px; /* 小屏幕时减少播放器高度 */
  }
  
  .recordings-content {
    padding: 0 12px 12px 12px; /* 小屏幕减少padding */
  }
}

@media (max-width: 768px) {
  .camera-list .ant-col {
    flex: 0 0 50%;
    max-width: 50%;
  }
  
  .list-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .player-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>
